package com.hbb20;

import com.hbb20.utils.SystemUtils;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ScrollView;
import ohos.agp.components.TextField;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;

public class FocusLine {
    /**
     * drawFocusLine
     *
     * @param textField textField
     * @param component component
     */
    public static void drawFocusLine(TextField textField, Component component) {

        textField.setFocusChangedListener((c, b) -> {
            drawFocusLine(b, component);
        });
    }

    /**
     * drawFocusLine
     *
     * @param textField  textField
     * @param component  component
     * @param scrollView scrollView
     */
    public static void drawFocusLine(TextField textField, Component component, ScrollView scrollView) {

        textField.setFocusChangedListener((c, b) -> {
            drawFocusLine(b, component);
            if (b) {
                int[] locationOnScreen = c.getLocationOnScreen();
                int y = locationOnScreen[1];
                int displayHight = SystemUtils.getDisplayHightInPx(c.getContext());
                scrollView.fluentScrollByY(y - displayHight / 2);
            }
        });
    }

    /**
     * drawFocusLine
     *
     * @param focus     focus
     * @param component component
     */
    public static void drawFocusLine(boolean focus, Component component) {
        if (focus) {
            focusAnimator(component);
        } else {
            setDefaultShape(component, RgbColor.fromArgbInt(Color.getIntColor("#cccccc")));
        }
    }

    private static void setDefaultShape(Component component, RgbColor color) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(color);
        component.setBackground(shapeElement);
    }

    private static void focusAnimator(Component component) {
        setLayoutConfig(component, 0);
        setDefaultShape(component, RgbColor.fromArgbInt(Color.getIntColor("#FF4081")));
        int width = component.getWidth();
        AnimatorValue focusAnimator = new AnimatorValue();
        focusAnimator.setDuration(300);
        focusAnimator.setValueUpdateListener((animatorValue, v) -> {
            setLayoutConfig(component, (int) (width * v));
        });
        focusAnimator.start();
    }


    private static void setLayoutConfig(Component component, int width) {
        ComponentContainer.LayoutConfig layoutConfig = component.getLayoutConfig();
        layoutConfig.width = width;
        component.setLayoutConfig(layoutConfig);
    }
}
